/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */

package org.osami.gateway.sensor.internal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Logger;

import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.Factory;
import org.apache.felix.ipojo.annotations.Bind;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.ServiceProperty;
import org.apache.felix.ipojo.annotations.Unbind;
import org.apache.felix.ipojo.annotations.Validate;
import org.osami.gateway.sensor.protocol.ConfigurationChangeListener;
import org.osami.gateway.sensor.protocol.ISensorDevice;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.device.Constants;
import org.osgi.service.device.Device;
import org.osgi.service.device.Driver;

/**
 * Created by IntelliJ IDEA.
 * User: guillaume
 * Date: 16 juin 2010
 * Time: 13:39:59
 * To change this template use File | Settings | File Templates.
 */
@Component
@Provides
@Instantiate
public class SensorDriver implements Driver, ConfigurationChangeListener {
    private static final Logger logger = Logger.getLogger(SensorDriver.class.getName());

    @ServiceProperty(name = Constants.DRIVER_ID,
                     value = "org.osami.driver.osamifrsensor-1.0")
    private String driverId;

    @Requires(filter = "(factory.name=org.osami.gateway.sensor.internal.temperature.TemperatureSense)")
    private Factory temperatureSenseFactory;

    @Requires(filter = "(factory.name=org.osami.gateway.sensor.internal.humidity.HumiditySense)")
    private Factory humiditySenseFactory;

    @Requires(filter = "(factory.name=org.osami.gateway.sensor.internal.light.LightSense)")
    private Factory lightSenseFactory;

    private BundleContext bundleContext;
    private Map<ServiceReference, ISensorDevice> devices;
    private Map<ServiceReference, List<ComponentInstance>> sensesMap;
    private Map<String, Dictionary<String, Object>> configurationMap;
    private List<String> attachedSerials;

    public SensorDriver(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
        this.attachedSerials = new ArrayList<String>();
        this.devices = new TreeMap<ServiceReference, ISensorDevice>();
        this.sensesMap = new TreeMap<ServiceReference, List<ComponentInstance>>();
        this.configurationMap = new TreeMap<String, Dictionary<String, Object>>();
    }

    @Validate
    private void start()
    {
        logger.info("SensorDriver " + this + " is starting");
    }

    @Invalidate
    private void stop()
    {
        logger.info("SensorDriver " + this + " is stopping");
    }

    @Bind(aggregate = true, optional = true)
    public synchronized void bindSensorDevice(ISensorDevice device, ServiceReference reference) throws Exception {
        logger.info("SensorDriver: bindSensorDevice" + reference);
        // Does this device belong to us ?
        int matches = match(reference);
        if (matches != Device.MATCH_NONE) {
            // It does, so let's store it.
            synchronized (devices) {
                devices.put(reference, device);
            }
        }
    }

    @Unbind
    public synchronized void unbindSensorDevice(ServiceReference reference) {
        logger.info("SensorDriver: unbindSensorDevice" + reference);
        ISensorDevice device = devices.get(reference);
        if (device != null) {
            synchronized (devices) {
                devices.remove(reference);
            }
        }
        else {
            logger.severe("SensorDriver: unbindSensorDevice: no such ServiceReference !");
        }
        List<ComponentInstance> senses = sensesMap.get(reference);
        if (senses != null) {
            synchronized (sensesMap) {
                for (ComponentInstance ci : senses) {
                    ci.dispose();
                }
                sensesMap.remove(reference);
            }
        }
        else {
            logger.severe("SensorDriver: unbindSensorDevice: no senses corresponding to this ServiceReference !");
        }
        String serial = (String) reference.getProperty(Constants.DEVICE_SERIAL);
        if (serial != null && attachedSerials.contains(serial)) {
            attachedSerials.remove(serial);
        }
        else {
            logger.severe("SensorDriver: unbindSensorDevice: no serial / unrecorded serial !");
        }
    }

    public synchronized int match(ServiceReference reference) throws Exception {
        logger.info("SensorDriver.match(" + reference + ")");
        String[] categories = (String[]) reference.getProperty(Constants.DEVICE_CATEGORY);
        if (categories != null) {
            if (Arrays.asList(categories).contains("OSAmIFRSensor")) {

                // This device belongs to us :)

                // First try an exact match with serial ...
                String serial = (String) reference.getProperty(Constants.DEVICE_SERIAL);
                if (serial != null) {
                    if (attachedSerials.contains(serial)) {
                        return SensorDevice.MATCH_SERIAL;
                    }
                }

                // Then try the "device.type" property.
                String type = (String) reference.getProperty("device.type");
                if (type != null) {
                    if ("osamifrsensor".equals(type)) {
                        return SensorDevice.MATCH_TYPE;
                    }
                }

            }
        }
        return Device.MATCH_NONE;
    }

    public synchronized String attach(final ServiceReference reference) throws Exception {
        logger.info("SensorDriver.attach(" + reference + ")");
        String[] categories = (String[]) reference.getProperty(Constants.DEVICE_CATEGORY);
        if (categories != null) {
            if (Arrays.asList(categories).contains("OSAmIFRSensor")) {
                // Attach the device
                String serial = (String) reference.getProperty(Constants.DEVICE_SERIAL);
                String topic = (String) reference.getProperty("topic");
                String expectedInstancePrefix = (String) reference.getProperty("instance.name") + "_";
                Map<String, String> values = (Map<String, String>) reference.getProperty("device.metadata");

                if (!attachedSerials.contains(serial)) {
                    attachedSerials.add(serial);

                    // Create senses according to the metadata.
                    Dictionary<String, Object> deviceIdFilter = new Hashtable<String, Object>();
                    List<ComponentInstance> senses = new ArrayList<ComponentInstance>();
                    deviceIdFilter.put("device", "(" + Constants.DEVICE_SERIAL + "=" + serial + ")");

                    for (String key : values.keySet()) {
                        ComponentInstance ci;
                        if (key.startsWith(SensorDevice.TEMPERATURE_KEY)) {
                            logger.info("Creating TemperatureSense for " + key);
                            Dictionary<String, Object> temperatureConfiguration = new Hashtable<String, Object>();
                            temperatureConfiguration.put("device.id", serial);
                            temperatureConfiguration.put("topic", topic + "/temperature");
                            temperatureConfiguration.put("sensor.type", "temperature");
                            temperatureConfiguration.put("sensor.model", values.get(key));
                            temperatureConfiguration.put("requires.filters", deviceIdFilter);
                            temperatureConfiguration.put("sense.id", key);
                            temperatureConfiguration.put("instance.name", expectedInstancePrefix + key);
                            ci = temperatureSenseFactory.createComponentInstance(temperatureConfiguration);
                            senses.add(ci);
                            configurationMap.put(expectedInstancePrefix + key, temperatureConfiguration);
                        }
                        else if (key.startsWith(SensorDevice.HUMIDITY_KEY)) {
                            logger.info("Creating HumiditySense for " + key);
                            Dictionary<String, Object> humidityConfiguration = new Hashtable<String, Object>();
                            humidityConfiguration.put("device.id", serial);
                            humidityConfiguration.put("topic", topic + "/humidity");
                            humidityConfiguration.put("sensor.type", "humidity");
                            humidityConfiguration.put("sensor.model", values.get(key));
                            humidityConfiguration.put("requires.filters", deviceIdFilter);
                            humidityConfiguration.put("sense.id", key);
                            humidityConfiguration.put("instance.name", expectedInstancePrefix + key);
                            ci = humiditySenseFactory.createComponentInstance(humidityConfiguration);
                            senses.add(ci);
                            configurationMap.put(expectedInstancePrefix + key, humidityConfiguration);
                        }
                        else if (key.startsWith(SensorDevice.LIGHT_KEY)) {
                            logger.info("Creating LightSense for " + key);
                            Dictionary<String, Object> lightConfiguration = new Hashtable<String, Object>();
                            lightConfiguration.put("device.id", serial);
                            lightConfiguration.put("topic", topic + "/light");
                            lightConfiguration.put("sensor.type", "light");
                            lightConfiguration.put("sensor.model", values.get(key));
                            lightConfiguration.put("requires.filters", deviceIdFilter);
                            lightConfiguration.put("sense.id", key);
                            lightConfiguration.put("instance.name", expectedInstancePrefix + key);
                            ci = lightSenseFactory.createComponentInstance(lightConfiguration);
                            senses.add(ci);
                            configurationMap.put(expectedInstancePrefix + key, lightConfiguration);
                        }
                        else {
                            logger.severe("Unknown sensor type !");
                        }
                    }

                    // Record *Sense instances
                    sensesMap.put(reference, senses);

                    try {
                        ServiceReference[] refs = bundleContext.getServiceReferences(ISensorDevice.class.getName(), "(instance.name=" + (String) reference.getProperty("instance.name") +")");
                        if (refs != null) {
                            ServiceReference ref = refs[0];
                            ISensorDevice sensorDevice = (ISensorDevice) (bundleContext.getService(reference));
                            sensorDevice.registerConfigurationChangeListener(this);
                        }
                    } catch (Exception e) {
                        // Should not happen
                        e.printStackTrace();
                    }

                }
                else {
                    logger.info("Trying to attach a device whose serial was already recorded, bailing out");
                }
            }
        }
        else {
            throw new Exception("SensorDriver does not know how to handle this device !");
        }

        // It is expected to return null if we have directly attached the device to our driver.
        return null;
    }

    public synchronized void configurationChanged(String serial) {
        logger.info("SensorDriver.configurationChanged(" + serial + ")");

        // Traverse the recorded ServiceReferences.
        for (ServiceReference reference : sensesMap.keySet()) {
            String refSerial = (String) reference.getProperty(Constants.DEVICE_SERIAL);
            if (refSerial.equals(serial)) {
                // Found the reference whose serial equals the one being reconfigured.
                List<ComponentInstance> senses = sensesMap.get(reference);
                // Let's reconfigure all senses.
                for (ComponentInstance ci : senses) {
                    String instanceName = ci.getInstanceName();
                    String expectedInstancePrefix = (String) reference.getProperty("instance.name") + "_";
                    Map<String, String> values = (Map<String, String>) reference.getProperty("device.metadata");

                    for (String key : values.keySet()) {
                        String expectedInstanceName = expectedInstancePrefix + key;
                        if (instanceName.equals(expectedInstanceName)) {
                            logger.info("Reconfiguring Sense for " + key);
                            Dictionary<String, Object> configuration = configurationMap.get(expectedInstanceName);
                            configuration.put("sensor.model", values.get(key));
                            ci.reconfigure(configuration);
                            configurationMap.put(expectedInstanceName, configuration);
                        }
                    }
                }
            }
        }
    }
}
